import { parseContactLatestChatRecord } from '@/services/contact-chat'
import { makeContactId, ContactType } from '@/services/contacts'
import type { ExternalContact } from '../externals'

/**
 * 原始转交数据
 */
export interface RawExternalTransfer {
  CreateTime: string
  FromUserId: string
  FromUserName: string
  Id: number
  Remark: string
  ToUserId: string
  ToUserName: string
  TransferWxId: string
  TransferWxName: string
  TransferWxIcon: string
  WxId: string
  WxCompanyName: string
  CorpId: string
  LastChatTimestamp: number
  LastChatMsg: string
  NewMsgCount?: number | null
}

export interface ExternalTransfer {
  isGive: boolean // 当前用户是转交者还是接收者
  id: number // 转交记录 id
  remark: string // 转交备注
  created: Date // 转交时间

  fromAccountId: string // 转交者用户 ID，如 internal-99（转交者为自己，代表是自己转交给别人；转交者不是自己，代表是别人转交给自己）
  fromName: string // 转交者名称
  toAccountId: string // 接收者用户 ID
  toName: string // 接收者名称
  transferWxid: string // 被转交客户的 wxid
  transferName: string // 被转交客户的名称
  transferAvatar: string // 被转交客户的头像
  ownerWxid: string // 被转交客户所属的企业微信 wxid
  ownerName: string // 被转交客户所属的企业微信名称
  ownerCorpId: string // 被转交客户所属的企业微信企业 ID
}

export interface TransferedExternal extends ExternalContact {
  transfer: ExternalTransfer
}

/**
 * 将转交信息格式化成联系人对象
 * TODO: 目前转交的客户只能显示出转交时提供的信息，例如无法显示备注名，也不会显示“删除标识“
 */
export function formatTransferedExternal(
  raw: RawExternalTransfer,
  userId: string,
): TransferedExternal {
  const transfer: ExternalTransfer = {
    isGive: userId === raw.FromUserId,
    id: raw.Id,
    remark: raw.Remark,
    created: new Date(raw.CreateTime),

    fromAccountId: raw.FromUserId,
    fromName: raw.FromUserName,
    toAccountId: raw.ToUserId,
    toName: raw.ToUserName,
    transferWxid: raw.TransferWxId,
    transferName: raw.TransferWxName,
    transferAvatar: raw.TransferWxIcon,
    ownerWxid: raw.WxId,
    ownerName: raw.WxCompanyName,
    ownerCorpId: raw.CorpId,
  }
  const conversationId = `S:${[transfer.ownerWxid, transfer.transferWxid]
    .map(v => parseInt(v, 10))
    .sort((a, b) => a - b)
    .join('_')}`
  return {
    type: ContactType.external,
    sex: 1, // TODO: 转交客户目前不知道性别信息，临时写死

    avatar: transfer.transferAvatar,
    contacted: raw.LastChatTimestamp,
    conversationId: `S:${[transfer.ownerWxid, transfer.transferWxid]
      .map(v => parseInt(v, 10))
      .sort((a, b) => a - b)
      .join('_')}`,
    describe: '',
    id: makeContactId(transfer.ownerWxid, transfer.transferWxid),
    name: transfer.transferName,
    ownerWxid: transfer.ownerWxid,
    remark: '',
    userId: transfer.transferWxid,
    deleted: null, // TODO: 目前转交客户不知道删除状态，也没有机制在删除状态改变时同步更新

    latestChat: raw.LastChatMsg
      ? parseContactLatestChatRecord({
          ownerWxid: raw.WxId,
          userId: transfer.transferWxid,
          conversationId,
          message: raw.LastChatMsg,
        }) ?? undefined
      : undefined,
    initialUnread: raw.NewMsgCount ?? 0,
    initialWarn: null,

    transfer,
  }
}
